package com.test.languagetest;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.classic.Session;

import com.pojo.Category;

/**
 * @description 级联删除
 * @author Leon Plious
 * @date 2020年7月3日
 */
public class HibernateTestCascadeDelete {

	
	/**
	 * @description
	 * @param args
	 * @date 2020年7月3日
	 */
	public static void main(String[] args) {
		SessionFactory sf = new Configuration().configure().buildSessionFactory();
		Session session = sf.openSession();
		session.beginTransaction();
		/*
Hibernate: select category0_.id as id2_0_, category0_.name as name2_0_ from category_ category0_ where category0_.id=?
Hibernate: select products0_.cid as cid2_1_, products0_.id as id1_, products0_.id as id0_0_, products0_.name as name0_0_, products0_.price as price0_0_, products0_.cid as cid0_0_ from product_ products0_ where products0_.cid=?
Hibernate: select users0_.pid as pid0_1_, users0_.uid as uid1_, user1_.id as id3_0_ from user_product users0_ inner join user_ user1_ on users0_.uid=user1_.id where users0_.pid=?
Hibernate: update product_ set cid=null where cid=?
Hibernate: delete from product_ where id=?
Hibernate: delete from category_ where id=?
		 */
		Category c = (Category) session.get(Category.class, 4);
		session.delete(c);
		
		// 看SQL可以分析，如果设值级联删除，则会将外表先删除相关数据，然后将本表数据删除
		// 如果有多个外表关联的话则会先更新未设置级联删除的表数据为null，然后再将设设置级联删除的按外主删除
		session.getTransaction().commit();
		session.close();
		sf.close();
	}
}
